package sunsun.xiaoli.jiarebang.device.pondteam;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.itboye.pondteam.base.BaseActivity;
import com.itboye.pondteam.bean.DeviceDetailModel;
import com.itboye.pondteam.bean.WeiShiModel;
import com.itboye.pondteam.custom.XAlertDialog;
import com.itboye.pondteam.custom.swipexpandlistview.expandablelistview.SwipeMenuExpandableCreator;
import com.itboye.pondteam.custom.swipexpandlistview.expandablelistview.SwipeMenuExpandableListView;
import com.itboye.pondteam.custom.swipexpandlistview.swipemenulistview.SwipeMenu;
import com.itboye.pondteam.custom.swipexpandlistview.swipemenulistview.SwipeMenuItem;
import com.itboye.pondteam.custom.wheelview.view.WheelPicker;
import com.itboye.pondteam.interfaces.IRecyclerviewclicklistener;
import com.itboye.pondteam.presenter.UserPresenter;
import com.itboye.pondteam.utils.LogUtils;
import com.itboye.pondteam.utils.loadingutil.MAlert;
import com.itboye.pondteam.volley.ResultEntity;
import com.itboye.pondteam.volley.TimesUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import sunsun.xiaoli.jiarebang.BuildConfig;
import sunsun.xiaoli.jiarebang.R;
import sunsun.xiaoli.jiarebang.adapter.SwipWeiShiadapter;
import sunsun.xiaoli.jiarebang.app.App;
import sunsun.xiaoli.jiarebang.utils.ComparePondFilterVersion;
import sunsun.xiaoli.jiarebang.utils.GsonUtil;

import static com.itboye.pondteam.presenter.UserPresenter.deviceSet_success;
import static com.itboye.pondteam.utils.ScreenUtil.getDimension;
import static com.itboye.pondteam.utils.StringFormatUtils.getFormatTime;
import static com.itboye.pondteam.volley.TimesUtils.*;
import static sunsun.xiaoli.jiarebang.utils.ComparePondFilterVersion.changeHostOrPort;
import static sunsun.xiaoli.jiarebang.utils.NumberUtils.getHHmmddStr;


public class ActivityChaZuoBDetail extends BaseActivity implements IRecyclerviewclicklistener, XAlertDialog.OnEditInputFinishedListener, Observer {

    private static final String FEEDER_PART_REQUEST = "feed_duration_success";
    //    RecyclerView recyclerview;
    TextView txt_title;
    ImageView img_back;
    ImageView img_add_weishi;
    private XAlertDialog xAlertDialog;
    ImageView chazuoB_weishi;
    private SwipeMenuExpandableListView exListView;
    App myApplication;
    private UserPresenter userPresenter;
    private ArrayList<WeiShiModel> arrayListInner;
    private SwipWeiShiadapter swipWeiShiadapter;
    private int groupPosition;
    boolean isUpdateUI = true;
    String chazuo_type = "A";
    private NumberPicker mHourSpinner, mMinuteSpinner, mSecondSpinner;
    private Calendar mDate;
    RelativeLayout re_mode_selection;
    TextView chazuoA_mode;
    private int tempType;
    //    public ArrayList<String> arB = new ArrayList<>(), arA = new ArrayList<>();
    private boolean isOpen;
    private View footerView;
    String did = "";
    private List<String> list;
    public long requestTime;
    Type typeToken = new TypeToken<ArrayList<WeiShiModel>>() {
    }.getType();
    TextView chazuo_A_total_power, chazuo_B_total_power;
    private String MODE_SET = "mode_set_success";
    TextView txt_right;
    private String RESET_SUCCESS = "reset_success";
    private NumberPicker numberPicker = null;
    Gson gson = GsonUtil.getSkipIdAndGroupIdGsonForPondTeamPeriod();
    int maxLength = 10;
    TextView tv_bottom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cha_zuo_bdetail);
        myApplication = (App) getApplication();
        myApplication.chazuoBDetail = this;
        arrayListInner = new ArrayList<>();
        if (BuildConfig.APP_TYPE.equalsIgnoreCase("pondteam")) {
            maxLength = 6;
            tv_bottom.setVisibility(View.GONE);
        }
        txt_right.setVisibility(View.VISIBLE);
        txt_right.setText(getString(R.string.reset));
        chazuo_type = getIntent().getStringExtra("chazuo_type");
        swipWeiShiadapter = new SwipWeiShiadapter(this, arrayListInner);
        swipWeiShiadapter.setChazuoType(chazuo_type);
        exListView.setAdapter(swipWeiShiadapter);
        if (myApplication.pondDeviceDetailUI != null) {
            did = myApplication.pondDeviceDetailUI.did;
            chazuo_A_total_power = myApplication.pondDeviceDetailUI.chazuo_A_total_power;
            chazuo_B_total_power = myApplication.pondDeviceDetailUI.chazuo_B_total_power;
        }
        userPresenter = new UserPresenter(this);
        if (BuildConfig.APP_TYPE.equalsIgnoreCase("pondteam".toLowerCase())) {
            changeHostOrPort(myApplication.pondDeviceDetailUI.deviceDetailModel.getVer(), userPresenter, null, ComparePondFilterVersion.isTrue(myApplication.pondDeviceDetailUI.deviceDetailModel.getVer()));
        }
        getModeValue();
        txt_title.setText(getIntent().getStringExtra("title"));
        SwipeMenuExpandableCreator creator = new SwipeMenuExpandableCreator() {
            @Override
            public void createGroup(SwipeMenu menu) {
                SwipeMenuItem item2 = new SwipeMenuItem(ActivityChaZuoBDetail.this);
                item2.setBackground(new ColorDrawable(getResources().getColor(R.color.red500)));
                item2.setWidth(getDimension(ActivityChaZuoBDetail.this, 90));
                item2.setTitle(getString(R.string.delete));
                item2.setTitleSize(18);
                item2.setTitleColor(Color.parseColor("#ffffff"));
                // item2.setIcon(R.drawable.ic_action_discard);
                menu.addMenuItem(item2);
            }

            @Override
            public void createChild(SwipeMenu menu) {
                // Create different menus depending on the footerView typeToken
            }
        };
        exListView.setOnSwipeListener(new SwipeMenuExpandableListView.OnSwipeListener() {
            @Override
            public void onSwipeStart(int position) {
                if (position != -1) {
                    //position!=-1代表有一栏已经打开
                    isOpen = true;
                }

            }

            @Override
            public void onSwipeEnd(int position) {
                if (position == -1) {
                    //position==-1代表没有有任何一栏打开，即所有分组全部是关闭状态
                    isOpen = false;
                }
            }
        });
        exListView.setMenuCreator(creator);
        exListView.setOnMenuItemClickListener((groupPosition, childPosition, menu, index) -> {
            deletePeriod(groupPosition);
            return true;
        });
        exListView.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> false);
        ////////////////尾部///////////////////////////
        footerView = View.inflate(this, R.layout.item_weishi_father, null);
        ImageView img_add_weishi = footerView.findViewById(R.id.img_add_weishi);
        img_add_weishi.setVisibility(View.VISIBLE);
        img_add_weishi.setOnClickListener(this);
        TextView txt_weishi_name = footerView.findViewById(R.id.txt_weishi_name);
        txt_weishi_name.setVisibility(View.GONE);
        TextView txt_weishi = footerView.findViewById(R.id.txt_weishi);
        txt_weishi.setText(getString(R.string.addnew_weishi));
        exListView.addFooterView(footerView);


        //////////////////头部//////////////////
        View viewHeader = View.inflate(this, R.layout.header_chazuo, null);
        re_mode_selection = viewHeader.findViewById(R.id.re_mode_selection);
        re_mode_selection.setOnClickListener(this);
        chazuoA_mode = viewHeader.findViewById(R.id.chazuoA_mode);
        exListView.addHeaderView(viewHeader);
        setChaZuoData();
    }

    private void deletePeriod(int groupPosition) {
        isConnect();
        try {
            arrayListInner.remove(groupPosition);
            String str3 = GsonUtil.getSkipIdAndGroupIdGsonForPondTeamPeriod().toJson(arrayListInner);
            if (chazuo_type.equals("A")) {
                userPresenter.deviceSet(did, -1, "", null, "", -1, "", "", "", "", "", "", "", "", "", -1, -1, "", "", "", str3, -1, -1, "");
            } else {
                userPresenter.deviceSet(did, tempType == 4 ? 1 : -1, null, "", "", -1, "", "", "", "", "", "", "", "", "", -1, -1, "", "", str3, "", -1, -1, "");
            }
            swipWeiShiadapter.notifyDataSetInvalidated();
            expandAll();
        } catch (Exception e) {
            MAlert.alert("error" + e.getMessage());
        }
    }

    ArrayList<WeiShiModel> arTemp = new ArrayList<>();

    private void getSocketValue() {
        DeviceDetailModel detailModelForTcp = new DeviceDetailModel();
        arTemp = new ArrayList<>();
        if (myApplication.pondDeviceDetailUI != null) {
            detailModelForTcp = myApplication.pondDeviceDetailUI.deviceDetailModel;
        }
        if (chazuo_type.equals("A")) {
            //插座A数据
            String period = detailModelForTcp.getOa_per();
            arTemp = GsonUtil.getSkipIdAndGroupIdGsonForPondTeamPeriod().fromJson(period, typeToken);
            if (tempType == 1) {
                if (arrayListInner == null) {
                    arrayListInner = new ArrayList<>();
                }
                arrayListInner.clear();
                exListView.removeFooterView(footerView);
                swipWeiShiadapter.notifyDataSetChanged();
            } else {
                if (exListView.getFooterViewsCount() >= 1) {

                } else {
                    exListView.addFooterView(footerView);
                }
                if (arrayListInner != null) {
                    arrayListInner.clear();
                    if (arTemp != null) {
                        arrayListInner.addAll(arTemp);
                        swipWeiShiadapter.notifyDataSetChanged();
                    }
                }
            }
        } else {
            //插座B数据
            //设置喂食时间
            String period = detailModelForTcp.getOb_per();
            Type type = new TypeToken<ArrayList<WeiShiModel>>() {
            }.getType();
            arTemp = GsonUtil.getSkipIdAndGroupIdGsonForPondTeamPeriod().fromJson(period, type);
            if (arrayListInner != null) {
                arrayListInner.clear();
                if (arTemp != null) {
                    arrayListInner.addAll(arTemp);
                    swipWeiShiadapter.notifyDataSetChanged();
                }
            }
        }
    }

    private void getModeValue() {
        int chaZuoBModeValue = 0;
        tempType = 0;
        DeviceDetailModel detailModelForTcp = new DeviceDetailModel();
        if (myApplication.pondDeviceDetailUI != null) {
            detailModelForTcp = myApplication.pondDeviceDetailUI.deviceDetailModel;
        }
        if (chazuo_type.equals("A")) {
            chaZuoBModeValue = Integer.parseInt(detailModelForTcp.getOut_state_a());
        } else {
            chaZuoBModeValue = Integer.parseInt(detailModelForTcp.getOut_state_b());
        }

        if ((chaZuoBModeValue & (int) Math.pow(2, 1)) == (int) Math.pow(2, 1)) {
            //自动模式
            tempType = 3;
            if (detailModelForTcp.getOb_timer() == 1 && chazuo_type.equals("B") && BuildConfig.APP_TYPE.equalsIgnoreCase("pondteam")) {
                tempType = 4;
            }
        } else {
            //手动模式
            if ((chaZuoBModeValue & (int) Math.pow(2, 0)) == (int) Math.pow(2, 0)) {
                //通电即为开
                tempType = 1;
            } else {
                //断电即为关
                tempType = 2;
            }
        }

        swipWeiShiadapter.setMode(tempType);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.img_back) {
            setResult();
        } else if (i == R.id.img_add_weishi) {
            isConnect();
            if (arrayListInner.size() >= maxLength) {
                MAlert.alert(String.format(getString(R.string.most_5), maxLength));
                return;
            }
            if (tempType != 3 && tempType != 4) {
                MAlert.alert(getString(R.string.turn_to_auto_mode));
                return;
            }
            xAlertDialog = new XAlertDialog(this, this);
            xAlertDialog.show();
            xAlertDialog.setType(0);//0为添加喂食

        } else if (i == R.id.re_weishi_closetime) {
            isConnect();

            groupPosition = (int) v.getTag();
            if (tempType == 4) {
                long beginTimeO = parseTimeToLong(arrayListInner.get(groupPosition).getSt(), "HHmmss");
                long endTimeO = parseTimeToLong(arrayListInner.get(groupPosition).getEt(), "HHmmss");
                int duration = (int) ((endTimeO - beginTimeO) / 1000);
                //设置喂食时长
                String[] weishi_single = new String[21];
                for (int i1 = 0; i1 < 20; i1++) {
                    weishi_single[i1] = "" + (i1 + 1);
                }
                showAlert(weishi_single, 2, duration);
                return;
            }
            if (tempType != 3) {
                MAlert.alert(getString(R.string.turn_to_auto_mode));
                return;
            }
            showTimerPicker(false);
        } else if (i == R.id.re_weishi_opentime) {
            isConnect();
            if (tempType != 3 && tempType != 4) {
                MAlert.alert(getString(R.string.turn_to_auto_mode));
                return;
            }
            groupPosition = (int) v.getTag();
            showTimerPicker(true);
        } else if (i == R.id.re_weishi_zhouqi) {
            isConnect();
            if (tempType != 3 && tempType != 4) {
                MAlert.alert(getString(R.string.turn_to_auto_mode));
                return;
            }
            groupPosition = (int) v.getTag();
            Intent intent = new Intent(this, WenDuPeriodActivity.class);
            intent.putExtra("title", getStringValue(com.itboye.pondteam.R.string.zhouqi));
            intent.putExtra("zhouqi", ((TextView) v.findViewById(R.id.txt_zhouqi_time)).getText().toString());
            startActivityForResult(intent, 101);
        } else if (i == R.id.re_mode_selection) {
            isConnect();
            showModeSelctionPopupWindow();
        } else if (i == R.id.txt_right) {
            showSaveDialog(0, 0);
        } else if (i == R.id.tv_delete) {
            showSaveDialog((Integer) v.getTag(), 1);
        }
    }

    private void showSaveDialog(final int i, int type) {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle(getString(R.string.tips));
        switch (type) {
            case 0:
                alert.setMessage(getString(R.string.socket_reset));
                break;
            case 1:
                alert.setMessage(getString(R.string.delete) + "?");
                break;
        }

        alert.setPositiveButton(getString(R.string.ok), (dialog, which) -> {
            switch (type) {
                case 0:
                    arrayListInner.clear();
                    String str3 = GsonUtil.getSkipIdAndGroupIdGsonForPondTeamPeriod().toJson(arrayListInner);
                    if (chazuo_type.equals("A")) {
                        userPresenter.deviceSet(did, -1, "", null, "", -1, "", "", "", "", "", "", "", "", "", -1, -1, "", "", "", str3, -1, -1, RESET_SUCCESS);
                    } else {
                        userPresenter.deviceSet(did, -1, null, "", "", -1, "", "", "", "", "", "", "", "", "", -1, -1, "", "", str3, "", -1, -1, RESET_SUCCESS)
                        ;
                    }
                    break;
                case 1:
                    deletePeriod(i);
                    break;
            }

        });
        alert.setNegativeButton(getString(R.string.cancel), null);
        alert.create();
        alert.show();
    }

    private void isConnect() {
        if (myApplication.pondDeviceDetailUI != null) {
            if (!myApplication.pondDeviceDetailUI.isConnect) {
                MAlert.alert(getString(R.string.disconnect));
                return;
            }
        }

    }

    private void showAlert(String[] arg1, int arg2, int selectIndex) {
        AlertDialog.Builder alert = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT);
        numberPicker = new NumberPicker(this);
//        numberPicker.setDisplayedValues(arg1);
        numberPicker.setMinValue(1);
        numberPicker.setMaxValue(arg1.length - 1);
        if (selectIndex != -1) {
            numberPicker.setValue(selectIndex);
        }
        //设置不可编辑
        numberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        alert.setView(numberPicker);
        alert.setPositiveButton(getStringValue(R.string.ok), (dialogInterface, i) -> {
            if (arg2 == 1) {

            } else if (arg2 == 2) {
                //设置喂食时长(通过开始时间和喂食时长设置结束时间)
                long beginTime = Long.parseLong(arrayListInner.get(groupPosition).getSt());//
                int duration = Integer.parseInt(arg1[numberPicker.getValue() - 1]);
                LogUtils.v("socket", "duration:" + duration + "  beginTime:" + beginTime);
                long endTime = beginTime + duration;
                LogUtils.v("socket", "endTime:" + endTime);
                String end = getHHmmddStr(endTime + "", 6);
                arrayListInner.get(groupPosition).setEt(parseTime(end, "HHmmss", "HHmmss"));
                LogUtils.v("socket", "endTimeLast:" + arrayListInner.get(groupPosition).getEt());
                String json = gson.toJson(arrayListInner);
                userPresenter.deviceSet(did, 1, null, null, "", -1, "", "", "", "", "", "", "", "", "", -1, -1, "", "", json, "", -1, -1, "");
            }
        });
        alert.setNegativeButton(getString(R.string.cancel), null);
        alert.show();
    }

    private void showModeSelctionPopupWindow() {
        AlertDialog.Builder alert = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT);
        View view = View.inflate(this, R.layout.item_mode_selection, null);
        final TextView txt_shoudong_open = view.findViewById(R.id.txt_shoudong_open);
        txt_shoudong_open.setTag(false);
        final TextView txt_shoudong_close = view.findViewById(R.id.txt_shoudong_close);
        txt_shoudong_close.setTag(false);
        final TextView txt_auto = view.findViewById(R.id.txt_auto);
        txt_auto.setTag(false);
        final TextView txt_feeder = view.findViewById(R.id.txt_feeder);
        txt_feeder.setTag(false);

        if (chazuo_type.equals("A") || !BuildConfig.APP_TYPE.equalsIgnoreCase("pondteam")) {
            txt_feeder.setVisibility(View.GONE);
        }
        switch (tempType) {
            case 1:
                txt_shoudong_open.setTextColor(getResources().getColor(R.color.main_green));
                txt_shoudong_open.setTag(true);
                break;
            case 2:
                txt_shoudong_close.setTextColor(getResources().getColor(R.color.main_green));
                txt_shoudong_close.setTag(true);
                break;
            case 3:
                txt_auto.setTextColor(getResources().getColor(R.color.main_green));
                txt_auto.setTag(true);
                break;
            case 4:
                txt_feeder.setTextColor(getResources().getColor(R.color.main_green));
                txt_feeder.setTag(true);
                break;
        }
        txt_shoudong_open.setOnClickListener(v -> setSelectColor(v, txt_shoudong_close, txt_auto, txt_feeder));
        txt_shoudong_close.setOnClickListener(v -> setSelectColor(v, txt_shoudong_open, txt_auto, txt_feeder));
        txt_auto.setOnClickListener(v -> setSelectColor(v, txt_shoudong_close, txt_shoudong_open, txt_feeder));
        txt_feeder.setOnClickListener(v -> setSelectColor(v, txt_shoudong_close, txt_shoudong_open, txt_auto));

        alert.setView(view);
        alert.setNegativeButton(getString(R.string.cancel), null);
        alert.setPositiveButton(getString(R.string.ok), (dialog, which) -> {
            isConnect();
            DeviceDetailModel detailModel = new DeviceDetailModel();
            if (myApplication.pondDeviceDetailUI != null) {
                detailModel = myApplication.pondDeviceDetailUI.deviceDetailModel;
            }
            /**
             * outStateA  outStateB
             *     Bit0：插座通电状态
             *   1：通电，0：断电
             *     Bit1：定时模式开关
             *   1：定时模式，0：手动模式
             *     Bit2：插座A节水使能标志
             *   1：节水使能，0：节水禁止
             */
            if ((Boolean) txt_shoudong_open.getTag()) {
                //手动模式开    01
                if (tempType == 1) {
                    MAlert.alert(getString(R.string.mode_isshoudong_open));
                } else {
                    if (chazuo_type.equals("A")) {//插座A数据
                        int value = Integer.parseInt(detailModel.getOut_state_a());
                        if ((value & (int) Math.pow(2, 0)) == 0) {
                            value = Integer.parseInt(detailModel.getOut_state_a()) ^ (int) Math.pow(2, 0);
                        }
                        if ((value & (int) Math.pow(2, 1)) == (int) Math.pow(2, 1)) {
                            value = value ^ (int) Math.pow(2, 1);
                        }
                        userPresenter.deviceSet(detailModel.getDid(), -1, null, null, "", -1, "", "", "", "", "", "", "", "", "", value, -1, "", "", "", "", -1, -1, MODE_SET);
                    } else {//插座B
                        int value = Integer.parseInt(detailModel.getOut_state_b());
                        if ((Integer.parseInt(detailModel.getOut_state_b()) & (int) Math.pow(2, 1)) == 0) {
                            value = Integer.parseInt(detailModel.getOut_state_b()) ^ (int) Math.pow(2, 0);
                        }
                        if ((Integer.parseInt(detailModel.getOut_state_b()) & (int) Math.pow(2, 1)) == (int) Math.pow(2, 1)) {
                            value = value ^ (int) Math.pow(2, 1);
                        }
                        userPresenter.deviceSet(detailModel.getDid(), 0, null, null, "", -1, "", "", "", "", "", "", "", "", "", -1, value, "", "", "", "", -1, -1, MODE_SET);
                    }
                }
                tempType = 1;
            } else if ((Boolean) txt_shoudong_close.getTag()) {
                //手动模式关
                if (tempType == 2) {
                    MAlert.alert(getString(R.string.mode_isshoudong_close));
                } else {
                    if (chazuo_type.equals("A")) {
                        int value = Integer.parseInt(detailModel.getOut_state_a());
                        if ((Integer.parseInt(detailModel.getOut_state_a()) & (int) Math.pow(2, 0)) == (int) Math.pow(2, 0)) {
                            value = Integer.parseInt(detailModel.getOut_state_a()) ^ (int) Math.pow(2, 0);
                        }
                        if ((Integer.parseInt(detailModel.getOut_state_a()) & (int) Math.pow(2, 1)) == (int) Math.pow(2, 1)) {
                            value = value ^ (int) Math.pow(2, 1);
                        }
                        userPresenter.deviceSet(detailModel.getDid(), -1, null, null, "", -1, "", "", "", "", "", "", "", "", "", value, -1, "", "", "", "", -1, -1, MODE_SET);
                    } else {
                        int value = Integer.parseInt(detailModel.getOut_state_b());
                        if ((Integer.parseInt(detailModel.getOut_state_b()) & (int) Math.pow(2, 0)) == (int) Math.pow(2, 0)) {
                            value = Integer.parseInt(detailModel.getOut_state_b()) ^ (int) Math.pow(2, 0);
                        }
                        if ((Integer.parseInt(detailModel.getOut_state_b()) & (int) Math.pow(2, 1)) == (int) Math.pow(2, 1)) {
                            value = value ^ (int) Math.pow(2, 1);
                        }
                        userPresenter.deviceSet(detailModel.getDid(), 0, null, null, "", -1, "", "", "", "", "", "", "", "", "", -1, value, "", "", "", "", -1, -1, MODE_SET);
                    }
                    tempType = 2;
                }

            } else if ((Boolean) txt_auto.getTag()) {
                if (tempType == 3) {
                    MAlert.alert(getString(R.string.mode_isauto));
                } else {
                    //自动模式
                    if (chazuo_type.equals("A")) {
                        int value = Integer.parseInt(detailModel.getOut_state_a()) ^ (int) Math.pow(2, 1);
                        userPresenter.deviceSet(detailModel.getDid(), -1, null, null, "", -1, "", "", "", "", "", "", "", "", "", value, -1, "", "", "", "", -1, -1, MODE_SET);
                    } else {
                        int value = Integer.parseInt(detailModel.getOut_state_b()) ^ (int) Math.pow(2, 1);
                        userPresenter.deviceSet(detailModel.getDid(), 0, null, null, "", -1, "", "", "", "", "", "", "", "", "", -1, value, "", "", "", "", -1, -1, MODE_SET);
                    }
                    tempType = 3;
                }

            } else if ((Boolean) txt_feeder.getTag()) {
                //插座B喂食模式
                if (tempType == 4) {
                    MAlert.alert(getString(R.string.mode_isfeed));
                    return;
                }
                tempType = 4;
                int outB = Integer.parseInt(detailModel.getOut_state_b());
                if (tempType != 3) {//如果模式定时模式，修改为定时模式传上去
                    outB = Integer.parseInt(detailModel.getOut_state_b()) ^ (int) Math.pow(2, 1);
                }
                userPresenter.deviceSet(detailModel.getDid(), 1, null, null, "", -1, "", "", "", "", "", "", "", "", "", -1, outB, "", "", "", "", -1, -1, MODE_SET);
            }
        });
        alert.create();
        alert.show();
    }

    private void setSelectColor(View v, TextView... t1) {
        TextView textView = (TextView) v;
        textView.setTag(true);
        textView.setTextColor(getResources().getColor(R.color.main_green));
        for (TextView view : t1) {
            view.setTextColor(getResources().getColor(R.color.black));
            view.setTag(false);
        }
    }

    WheelPicker myNumberPickerView;

    private void showTimerPicker(final boolean type) {
        View viewPicker = View.inflate(this, R.layout.timer_picker, null);
        mDate = Calendar.getInstance();
        int mHour;
        int mMinute;
        int mSecond;
        if (type) {
            mHour = Integer.parseInt(getFormatTime(arrayListInner.get(groupPosition).getSt()).split(":")[0]);
            mMinute = Integer.parseInt(getFormatTime(arrayListInner.get(groupPosition).getSt()).split(":")[1]);
            mSecond = Integer.parseInt(getFormatTime(arrayListInner.get(groupPosition).getSt()).split(":")[2]);
        } else {
            mHour = Integer.parseInt(getFormatTime(arrayListInner.get(groupPosition).getEt()).split(":")[0]);
            mMinute = Integer.parseInt(getFormatTime(arrayListInner.get(groupPosition).getEt()).split(":")[1]);
            mSecond = Integer.parseInt(getFormatTime(arrayListInner.get(groupPosition).getEt()).split(":")[2]);

        }
        myNumberPickerView = viewPicker.findViewById(R.id.number_picker1);
        list = Arrays.asList(getResources().getStringArray(R.array.apm));
        myNumberPickerView.setData(list);

        mHourSpinner = viewPicker.findViewById(R.id.timerHours);
        mHourSpinner.setMaxValue(23);
        mHourSpinner.setMinValue(0);
        mHourSpinner.setValue(Integer.parseInt(utc2Local(mHour + "", "HH", "HH")));
        mHourSpinner.setFormatter(formatter);
        mHourSpinner.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);

        mMinuteSpinner = viewPicker.findViewById(R.id.timerMinutes);
        mMinuteSpinner.setMaxValue(59);
        mMinuteSpinner.setMinValue(0);
        mMinuteSpinner.setValue(mMinute);
        mMinuteSpinner.setFormatter(formatter);
        mMinuteSpinner.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);

        mSecondSpinner = viewPicker.findViewById(R.id.timerSeconds);
        mSecondSpinner.setMaxValue(59);
        mSecondSpinner.setMinValue(0);
        mSecondSpinner.setValue(mSecond);
        mSecondSpinner.setFormatter(formatter);
        mSecondSpinner.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        mSecondSpinner.setOnValueChangedListener(mOnSecondChangedListener);
        AlertDialog.Builder alert = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT);
        alert.setTitle(type ? getString(R.string.chazuo_open_time) : getString(R.string.chazuo_close_time)).setView(viewPicker).setPositiveButton(getString(R.string.ok), (dialog, which) -> {
            isConnect();
            String hour = getHHmmddStr(mHourSpinner.getValue() + "", 2);
            hour = TimesUtils.localToUTC(hour + "", "HH", "HH");
//            LogUtils.v("gg", "过滤桶时段设置  mHour：" + mHour + "mMinute" + mMinute + " mSecond" + mSecond);
            boolean isEqual = comparePeriod(type, Integer.parseInt(hour), mMinuteSpinner.getValue(), mSecondSpinner.getValue());
            if (isEqual) {
                MAlert.alert(getStringValue(R.string.socket_time_repeat));
                return;
            }
            String value = hour + "" + getHHmmddStr(mMinuteSpinner.getValue() + "", 2) + "" + getHHmmddStr(mSecondSpinner.getValue() + "", 2);
            LogUtils.v("socket", "原始选中的beginTime:" + value);
            if (type) {
                long beginTimeO = parseTimeToLong(getHHmmddStr(arrayListInner.get(groupPosition).getSt(), 6), "HHmmss");
                LogUtils.v("socket", "原始beginTime:" + beginTimeO);
                long endTimeO = parseTimeToLong(getHHmmddStr(arrayListInner.get(groupPosition).getEt(), 6), "HHmmss");
                LogUtils.v("socket", "原始endTime:" + endTimeO);
                long duration = (endTimeO - beginTimeO) / 1000;
                LogUtils.v("socket", "喂食时长:" + duration);
                arrayListInner.get(groupPosition).setSt(value);
                if (tempType == 4) {//喂食模式根据喂食开始时间和喂食时长计算重新设置结束时间
                    long beginTime = Long.parseLong(arrayListInner.get(groupPosition).getSt());//
                    LogUtils.v("socket", "修改后beginTime:" + beginTime);
                    long endTime = beginTime + duration;
                    String end = getHHmmddStr(endTime + "", 6);
                    LogUtils.v("socket", "修改后endTime:" + end);
                    arrayListInner.get(groupPosition).setEt(parseTime(end, "HHmmss", "HHmmss"));
                }
            } else {
                arrayListInner.get(groupPosition).setEt(value);
            }
            String json = GsonUtil.getSkipIdAndGroupIdGsonForPondTeamPeriod().toJson(arrayListInner);
            if (chazuo_type.equals("A")) {
                userPresenter.deviceSet(did, -1, null, null, "", -1, "", "", "", "", "", "", "", "", "", -1, -1, "", "", "", json, -1, -1, "");
            } else {
                userPresenter.deviceSet(did, tempType == 4 ? 1 : -1, null, null, "", -1, "", "", "", "", "", "", "", "", "", -1, -1, "", "", json, "", -1, -1, "");
            }
        }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> {

        }).show();
    }

    private boolean comparePeriod(boolean isOpen, int hour, int minute, int second) {
        boolean isEqual = false;
        String cTimeFormatSt[] = getFormatTime(arrayListInner.get(groupPosition).getSt()).split(":");
        String cTimeFormatEt[] = getFormatTime(arrayListInner.get(groupPosition).getEt()).split(":");
        LogUtils.v("gg", "过滤桶时段设置  mHour：" + hour + " mMinute:" + minute + " mSecond:" + second);
        for (int i = 0; i < arrayListInner.size(); i++) {
            WeiShiModel weiShiModel = arrayListInner.get(i);
            String timeFormatSt[] = getFormatTime(weiShiModel.getSt()).split(":");
            String timeFormatEt[] = getFormatTime(weiShiModel.getEt()).split(":");
            LogUtils.v("gg", "过滤桶时段开启时间  mHour：" + timeFormatSt[0] + " mMinute:" + timeFormatSt[1] + " mSecond:" + timeFormatSt[2]);
            LogUtils.v("gg", "过滤桶时段关闭时间  mHour：" + timeFormatEt[0] + " mMinute:" + timeFormatEt[1] + " mSecond:" + timeFormatEt[2]);
            if (isOpen) {
                if (hour == Integer.parseInt(timeFormatSt[0]) && minute == Integer.parseInt(timeFormatSt[1]) && second == Integer.parseInt(timeFormatSt[2])) {
                    if (Integer.parseInt(cTimeFormatEt[0]) == Integer.parseInt(timeFormatEt[0]) && Integer.parseInt(cTimeFormatEt[1]) == Integer.parseInt(timeFormatEt[1]) && Integer.parseInt(cTimeFormatEt[2]) == Integer.parseInt(timeFormatEt[2])) {
                        MAlert.alert("时段不能重复");
                        isEqual = true;
                        break;
                    }
                }
            } else {
                if (hour == Integer.parseInt(timeFormatEt[0]) && minute == Integer.parseInt(timeFormatEt[1]) && second == Integer.parseInt(timeFormatEt[2])) {
                    if (Integer.parseInt(cTimeFormatSt[0]) == Integer.parseInt(timeFormatSt[0]) && Integer.parseInt(cTimeFormatSt[1]) == Integer.parseInt(timeFormatSt[1]) && Integer.parseInt(cTimeFormatSt[2]) == Integer.parseInt(timeFormatSt[2])) {
                        MAlert.alert("时段不能重复");
                        isEqual = true;
                        break;
                    }
                }
            }
        }

        return isEqual;
    }

    private NumberPicker.OnValueChangeListener mOnHourChangedListener = (picker, oldVal, newVal) -> {

    };
    private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = (picker, oldVal, newVal) -> {

    };
    private NumberPicker.OnValueChangeListener mOnSecondChangedListener = (picker, oldVal, newVal) -> {

    };
    //数字格式化，<10的数字前自动加0
    private NumberPicker.Formatter formatter = value -> {
        String Str = String.valueOf(value);
        if (value < 10) {
            Str = "0" + Str;
        }
        return Str;
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == 102) {
            requestTime = System.currentTimeMillis();
            isConnect();
            int weekBinary = data.getIntExtra("weekBinary", 0);
            arrayListInner.get(groupPosition).setWeek(weekBinary);
            String json = GsonUtil.getSkipIdAndGroupIdGsonForPondTeamPeriod().toJson(arrayListInner);
            if (chazuo_type.equalsIgnoreCase("A")) {
                userPresenter.deviceSet(did, -1, null, null, "", -1, "", "", "", "", "", "", "", "", "", -1, -1, "", "", "", json, -1, -1, deviceSet_success);
            } else if (chazuo_type.equalsIgnoreCase("B")) {
                userPresenter.deviceSet(did, tempType == 4 ? 1 : -1, null, null, "", -1, "", "", "", "", "", "", "", "", "", -1, -1, "", "", json, "", -1, -1, deviceSet_success);
            }
            swipWeiShiadapter.notifyDataSetInvalidated();
        }
    }

    @Override
    public void onItemClick(String str) {

    }

    @Override
    public void onLeftMenuClick(String str) {

    }

    @Override
    public void onRightMenuClick(String str) {
        MAlert.alert(str);
    }

    @Override
    public void editInputFinished(String password) {
        isConnect();
        try {
            WeiShiModel weishi = new WeiShiModel();
            //////////nickName修改//////////////
            ArrayList<WeiShiModel> arrayTemp = new ArrayList<>();
            if (xAlertDialog.getType() == 1) {
                arrayListInner.get(groupPosition).setNick_name(password);
                arrayTemp = arrayListInner;
            } else {
                String hour = TimesUtils.localToUTC(0 + "", "HH", "HH");
                weishi.setNick_name(password);
                weishi.setSt(hour + "0000");
                weishi.setEt(hour + "0000");
                weishi.setWeek(4);
                if (arrayListInner == null) {
                    arrayListInner = new ArrayList<>();
                }
                arrayTemp.add(weishi);
                arrayListInner.addAll(arrayTemp);
                swipWeiShiadapter.notifyDataSetInvalidated();
            }
            String json = GsonUtil.getSkipIdAndGroupIdGsonForPondTeamPeriod().toJson(arrayListInner);
            hasEx = false;
            if (myApplication.pondDeviceDetailUI != null) {
                if (chazuo_type.equals("A")) {
                    userPresenter.deviceSet(did, -1, "", null, "", -1, "", "", "", "", "", "", "", "", "", -1, -1, "", "", "", json, -1, -1, "");
                } else {
                    userPresenter.deviceSet(did, tempType == 4 ? 1 : -1, null, "", "", -1, "", "", "", "", "", "", "", "", "", -1, -1, "", "", json, "", -1, -1, "");
                }
            }

        } catch (Exception e) {

        }
        xAlertDialog.dismiss();
        expandAll();
    }

    boolean hasEx = false;


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setResult() {
        Intent intent = new Intent();
        intent.putExtra("typeToken", chazuo_type);
        intent.putExtra("value", tempType);
        setResult(102, intent);
        finish();
    }

    public void setChaZuoData() {
        getSocketValue();
//        getModeValue();
        setMode();
        expandAll();

    }

    private void expandAll() {
        if (swipWeiShiadapter != null) {
            for (int i = 0; i < swipWeiShiadapter.getGroupCount(); i++) {
                exListView.expandGroup(i);// 关键步骤3,初始化时，将ExpandableListView以展开的方式呈现
            }
        }
    }

    private void setMode() {
        if (tempType == 3) {
            //自动模式
//            if (chazuo_type.equalsIgnoreCase("a")) {
//                chazuo_A_total_power.setText(Html.fromHtml(getString(R.string.status) + "<font color='#45B380'>" + getString(R.string.mode_zidong)+ "</font>"));
//            } else {
//                chazuo_B_total_power.setText(Html.fromHtml(getString(R.string.status) + "<font color='#45B380'>" + getString(R.string.mode_zidong)+ "</font>"));
//            }
            chazuoA_mode.setText(getString(R.string.dingshimoshi));
        } else if (tempType == 1) {
            //手动模式
            //通电即为开
            chazuoA_mode.setText(getString(R.string.mode_shoudong_open));
//            if (chazuo_type.equalsIgnoreCase("a")) {
//                chazuo_A_total_power.setText(Html.fromHtml(getString(R.string.status) + "<font color='#45B380'>" + getString(R.string.mode_shoudong_open)+ "</font>"));
//            } else {
//                chazuo_B_total_power.setText(Html.fromHtml(getString(R.string.status) + "<font color='#45B380'>" + getString(R.string.mode_shoudong_open)+ "</font>"));
//            }
        } else if (tempType == 2) {
            //断电即为关
            chazuoA_mode.setText(getString(R.string.mode_shoudong_close));
//            if (chazuo_type.equalsIgnoreCase("a")) {
//                chazuo_A_total_power.setText(Html.fromHtml(getString(R.string.status) + "<font color='#45B380'>" + getString(R.string.mode_shoudong_close)+ "</font>"));
//            } else {
//                chazuo_B_total_power.setText(Html.fromHtml(getString(R.string.status) + "<font color='#45B380'>" + getString(R.string.mode_shoudong_close)+ "</font>"));
//            }
        } else if (tempType == 4) {
            chazuoA_mode.setText(getString(R.string.mode_feed));

        }
        swipWeiShiadapter.setMode(tempType);
    }

    @Override
    public void update(Observable o, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getCode() != 0) {
                MAlert.alert(entity.getMsg());
                return;
            }
            if (entity.getEventType() == deviceSet_success) {
                isOpen = false;
                swipWeiShiadapter.notifyDataSetChanged();
                requestTime = System.currentTimeMillis();
                MAlert.alert(entity.getData());
//                if (myApplication.pondDeviceDetailUI != null) {
//                    myApplication.pondDeviceDetailUI.beginRequst();
//                } else if (myApplication.pondDeviceDetailForXiaoLiUI != null) {
//                    myApplication.pondDeviceDetailForXiaoLiUI.beginRequst();
//                }
            } else if (entity.getEventType() == UserPresenter.deviceSet_fail) {
                MAlert.alert(entity.getData());
            } else if (entity.getEventType() == MODE_SET) {
                if (myApplication.pondDeviceDetailUI != null) {
                    myApplication.pondDeviceDetailUI.beginRequst();
                }
//                else if(){
//                    myApplication.pondDeviceDetailUI.beginRequst();
//                }
                getSocketValue();
                setMode();
                MAlert.alert(entity.getData());
            } else if (entity.getEventType() == RESET_SUCCESS) {
                swipWeiShiadapter.notifyDataSetInvalidated();
                MAlert.alert(entity.getData());
            } else if (entity.getEventType() == FEEDER_PART_REQUEST) {
                MAlert.alert(entity.getData());
            }
        }
    }

}
